package com.wondream.myframework.app.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import com.wondream.myframework.app.dao.LitemallUserMapper;
import com.wondream.myframework.app.common.util.JacksonUtil;
import org.apache.ibatis.builder.xml.XMLMapperBuilder;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;

public class MybatisDemo2 {
    public static void main(String[] args) throws Exception {
        DataSource dataSource = getDataSource();
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        Environment env = new Environment("dev", transactionFactory, dataSource);
        Configuration configuration = new Configuration(env);
        configuration.addMapper(LitemallUserMapper.class);
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis/mybatis-config.xml");
        XMLMapperBuilder xmlParser = new XMLMapperBuilder(resourceAsStream, configuration, "com/wondream/myframework/app/dao/LitemallUserMapper.xml", configuration.getSqlFragments(), "com.wondream.myframework.app.dao.LitemallUserMapper");
        xmlParser.parse();
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        LitemallUserMapper userMapper = sqlSession.getMapper(LitemallUserMapper.class);
        System.out.println(JacksonUtil.toJson(userMapper.selectByPrimaryKey(1)));

    }

    private static DataSource getDataSource() throws Exception {
        InputStream resourceAsStream = Resources.getResourceAsStream("mybatis/druid.properties");

        DruidDataSource druidDataSource = new DruidDataSource();
        Properties properties = new Properties();
        properties.load(resourceAsStream);
        druidDataSource.configFromPropety(properties);
        return druidDataSource;
    }


}
